package com.ltsznh.android.familybooks.record;

import android.app.ActionBar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.ContentValues;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.ltsznh.android.familybooks.MainActivity;
import com.ltsznh.android.familybooks.R;
import com.ltsznh.android.familybooks.db.dbo;

import java.util.Calendar;

public class EditRecordActivity extends Activity {

    protected String invDate = MainActivity.dayString;
    protected String invType = "O";
    protected String invCategory = "";
    protected String invCategory2 = "";
    protected String accountCategory = "";
    protected String account = "";

    protected final ContentValues values = new ContentValues();
    private Spinner categorySpinner;
    private ArrayAdapter<String> categoryAdapter;
    private Spinner category2Spinner;
    private ArrayAdapter<String> category2Adapter;
    private Spinner accountCategorySpinner;
    private ArrayAdapter<String> accountAdapter;
    private Spinner accountSpinner;
    private ArrayAdapter<String> accountCategoryAdapter;

    private int editId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record);

        ActionBar actionBar = this.getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);

        invType = getIntent().getStringExtra("invType");

        initDate();
        initCategory();
        initAccount();

        editId = getIntent().getIntExtra("id",-1);
        if(editId > -1){
            initDefaultValue(editId);
        }
    }

    private void initDefaultValue(Integer id) {
        String sqlString = "select id,invDate,entryTime,invPicture,yuan," +
                "invType,invCategory,invCategory2,accountCategory,account,remark,isInvalid,place," +
                "longitude,latitude,accuracy,placeTime from inv_blotters where id = " + id;
        dbo.getReadableDatabase(this);
        Cursor editCursor = dbo.fbSQLite.rawQuery(sqlString, null);

        if(editCursor.getCount()>0){
            editCursor.moveToFirst();

            invDate = editCursor.getString(editCursor.getColumnIndex("invDate"));
            initDate();

            invCategory = editCursor.getString(editCursor.getColumnIndex("invCategory"));
            int i = categoryAdapter.getCount();
            for(int j = 0;j < i;j++){
                if(categoryAdapter.getItem(j).equalsIgnoreCase(invCategory)){
                    categorySpinner.setSelection(j,true);
                };
            }

            accountCategory = editCursor.getString(editCursor.getColumnIndex("accountCategory"));
            i = accountCategoryAdapter.getCount();
            for(int j = 0;j < i;j++){
                if(accountCategoryAdapter.getItem(j).equalsIgnoreCase(accountCategory)){
                    accountCategorySpinner.setSelection(j,true);
                };
            }
        }

        ((EditText)findViewById(R.id.editText_record_yuan)).setText(editCursor.getDouble(editCursor.getColumnIndex("yuan")) + "");
        ((EditText)findViewById(R.id.editText_record_place)).setText(editCursor.getString(editCursor.getColumnIndex("place")) + "");
        ((EditText)findViewById(R.id.editText_record_remark)).setText(editCursor.getString(editCursor.getColumnIndex("remark")) + "");

        editCursor.close();
        dbo.closeDatabase();

    }

    public void selectDate(View view){
        DatePickerDialog.OnDateSetListener test = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int month, int day) {
                Calendar invCalendar = Calendar.getInstance();
                invCalendar.set(year,month,day);
                invDate = MainActivity.format.format(invCalendar.getTime());
                initDate();
            }
        };

        DatePickerDialog invDatePicker;
        invDatePicker = new DatePickerDialog(this,test,Integer.parseInt(invDate.substring(0,4)),
                Integer.parseInt(invDate.substring(5,7)) - 1,Integer.parseInt(invDate.substring(8,10)));
        invDatePicker.show();
    }

    private void initDate() {
        EditText invDateText = (EditText) findViewById(R.id.editText_record_date);
        invDateText.setText(invDate);
    }

    private void initCategory(){
        //类别1
        categorySpinner = (Spinner) findViewById(R.id.spinner_record_category);
        categoryAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
        categoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        categorySpinner.setAdapter(categoryAdapter);

        //类别2
        category2Spinner = (Spinner) findViewById(R.id.spinner_record_category2);
        category2Adapter = new ArrayAdapter<String>(EditRecordActivity.this, android.R.layout.simple_spinner_item);
        category2Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        category2Spinner.setAdapter(category2Adapter);

        String sqlString = "SELECT distinct invCategory FROM inv_category where isEnabled = 'Y' AND invType='" + invType + "' order by displayOrder";
        dbo.getReadableDatabase(this);
        Cursor CategoryCursor = dbo.fbSQLite.rawQuery(sqlString, null);
        if(CategoryCursor.getCount()>0){
            CategoryCursor.moveToFirst();
            do{
                categoryAdapter.add(CategoryCursor.getString(0));
            }while (CategoryCursor.moveToNext());
        }
        CategoryCursor.close();
        dbo.closeDatabase();

        categorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                invCategory = categoryAdapter.getItem(i);
                selectCategory2();
            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {}
        });
    }

    private void selectCategory2() {
        category2Adapter.clear();
        String sqlString = "SELECT distinct invCategory2 FROM inv_category where isEnabled = 'Y' AND invType='" + invType + "' " +
                "AND invCategory ='" + invCategory + "' order by displayOrder";
        dbo.getReadableDatabase(EditRecordActivity.this);
        Cursor category2Cursor = dbo.fbSQLite.rawQuery(sqlString, null);
        if(category2Cursor.getCount()>0){
            category2Cursor.moveToFirst();
            do{
                category2Adapter.add(category2Cursor.getString(0));
            }while (category2Cursor.moveToNext());
        }
        category2Cursor.close();
        dbo.closeDatabase();

        category2Spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                invCategory2 = category2Adapter.getItem(i);
            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) { }
        });
        initDefaultCategory2();
    }

    private void initDefaultCategory2(){
        String sqlString = "select id,invDate,entryTime,invPicture,yuan," +
                "invType,invCategory,invCategory2,accountCategory,account,remark,isInvalid,place," +
                "longitude,latitude,accuracy,placeTime from inv_blotters where id = " + editId;
        dbo.getReadableDatabase(this);
        Cursor editCursor = dbo.fbSQLite.rawQuery(sqlString, null);
        if(editCursor.getCount()>0){
            editCursor.moveToFirst();
            String invCategory2Tmp = editCursor.getString(editCursor.getColumnIndex("invCategory2"));
            int i = category2Adapter.getCount();
            category2Spinner.setSelection(0,true);
            for(int j = 0;j < i;j++){
                if(category2Adapter.getItem(j).equalsIgnoreCase(invCategory2Tmp)){
                    category2Spinner.setSelection(j,true);
                };
            }
        }
        editCursor.close();
        dbo.closeDatabase();
    }

    private void initAccount() {
        //账户类别
        accountCategorySpinner = (Spinner) findViewById(R.id.spinner_record_accountCategory);
        accountCategoryAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
        accountCategoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        accountCategorySpinner.setAdapter(accountCategoryAdapter);

        //账户
        accountSpinner = (Spinner) findViewById(R.id.spinner_record_account);
        accountAdapter = new ArrayAdapter<String>(EditRecordActivity.this, android.R.layout.simple_spinner_item);
        accountAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        accountSpinner.setAdapter(accountAdapter);

        String sqlString = "select distinct accountCategory from inv_account where isEnabled ='Y' order by displayOrder";
        dbo.getReadableDatabase(this);
        Cursor accountCategoryCursor = dbo.fbSQLite.rawQuery(sqlString, null);
        if(accountCategoryCursor.getCount()>0){
            accountCategoryCursor.moveToFirst();
            do{
                accountCategoryAdapter.add(accountCategoryCursor.getString(0));
            }while (accountCategoryCursor.moveToNext());
        }
        accountCategoryCursor.close();
        dbo.closeDatabase();

        accountCategorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                accountCategory = accountCategoryAdapter.getItem(i);
                selectAccount();
            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {}
        });
    }

    private void selectAccount() {
        accountAdapter.clear();
        String sqlString = "select distinct account from inv_account where isEnabled ='Y' " +
                "and accountCategory ='" + accountCategory + "'  order by displayOrder";
        dbo.getReadableDatabase(EditRecordActivity.this);
        Cursor accountCursor = dbo.fbSQLite.rawQuery(sqlString, null);
        if(accountCursor.getCount()>0){
            accountCursor.moveToFirst();
            do{
                accountAdapter.add(accountCursor.getString(0));
            }while (accountCursor.moveToNext());
        }
        accountCursor.close();
        dbo.closeDatabase();

        accountSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                account = accountAdapter.getItem(i);
            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {}
        });
        initDefaultAccount();
    }

    private void initDefaultAccount(){
        String sqlString = "select id,invDate,entryTime,invPicture,yuan," +
                "invType,invCategory,invCategory2,accountCategory,account,remark,isInvalid,place," +
                "longitude,latitude,accuracy,placeTime from inv_blotters where id = " + editId;
        Log.d(this.getLocalClassName(),sqlString);
        Log.d(this.getLocalClassName() + "TTT",category2Adapter.getCount() + "");
        dbo.getReadableDatabase(this);
        Cursor editCursor = dbo.fbSQLite.rawQuery(sqlString, null);
        Log.d(this.getLocalClassName(), "category2/" + editCursor.getCount() + "/" + category2Adapter.getCount() + "/" + categoryAdapter.getCount());

        if(editCursor.getCount()>0){
            editCursor.moveToFirst();
            String accountTmp = editCursor.getString(editCursor.getColumnIndex("account"));
            int i = accountAdapter.getCount();
            accountSpinner.setSelection(0,true);
            for(int j = 0;j < i;j++){
                if(accountAdapter.getItem(j).equalsIgnoreCase(accountTmp)){
                    accountSpinner.setSelection(j,true);
                };
            }
        }
        editCursor.close();
        dbo.closeDatabase();
    }

    private void initDataValue() {
        values.put("invDate",invDate);
        values.put("invType",invType);

        values.put("invCategory",invCategory);
        values.put("invCategory2",invCategory2);
        values.put("accountCategory",accountCategory);
        values.put("account",account);

        values.put("yuan",((EditText) findViewById(R.id.editText_record_yuan)).getText().toString());
        values.put("place",((EditText) findViewById(R.id.editText_record_place)).getText().toString());
        values.put("remark",((EditText) findViewById(R.id.editText_record_remark)).getText().toString());
    }

    public void saveData(View view){
        initDataValue();
        long i = dbo.updateData(this, "inv_blotters", values, "id = " + editId, null);
        if(i == -1){
            Toast.makeText(this,"ERROR",Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(this,"OK",Toast.LENGTH_SHORT).show();
            goBack();
        }
    }

    protected void goBack(){
        Log.d(this.getClass().toString(),  "to home");
//        Intent intent = new Intent(this, BlottersActivity.class);
//        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//        startActivity(intent);
        EditRecordActivity.this.finish();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        switch (item.getItemId()){
            case android.R.id.home:
                goBack();
                return true;
            case R.id.action_in:
                Log.d(this.getClass().toString(), "action in");
                invType = "I";
                initCategory();
                return true;
            case R.id.action_out:
                Log.d(this.getClass().toString(), "action out");
                invType = "O";
                initCategory();
                return true;
            default:
                Log.d(this.getClass().toString(),"nothing");
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.record, menu);
        return true;
    }
}
